let app = getApp();
Page({
  data: {
    userCode: "",
    URL:[{}]
  },
  onLoad() {
    this.obtainCode();
  },
  obtainCode: function() {
    let that = this;
    wx.login({      
      success(res) {
        that.setData({
          userCode: res.code
        });
      },
      fail() {
        //TODO 错误提示
        this.obtainCode();
        app.toast("未知错误,重新获取中");
      }
    })
  },
  register(){
    var url = "/pages/login/login";
    wx.navigateTo({ url: url });
  },
  login(res) {
    //解构
    let that = this;
    let {
      iv,
      encryptedData
    } = res.detail;
    if (iv && encryptedData) {
      wx.login({
        success(res) {
          let code = that.data.userCode;
          app.post("login", {
              iv,
              code,
              encryptedData
            })
            .then((res) => {
              wx.hideNavigationBarLoading();
              if (res.code == 200) {
                app.setUserInfo(res.data);
                app.toast(res.message);
                wx.navigateTo({ url: '/pages/index/index' });
              } else {
                app.toast(res.message);
              }
            })
            .catch((e) => {
              wx.showNavigationBarLoading();
              app.toast("网络或服务器错误～");
            })
        },
        fail() {
          //TODO 错误提示
          wx.showNavigationBarLoading();
          app.toast("未知错误，请重启微信试试。");
        }
      })
    } else {
      app.toast("请允许授权登录");
    }
  }
})